package imvu.rbox.object
{
	import anshe.event.TitleEvent;
	
	import flash.display.MovieClip;
	import flash.display.SimpleButton;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import imvu.rbox.event.ActionEvent;
	import imvu.rbox.event.BoxEvent;
	import imvu.rbox.global.GStatic;
	import imvu.rbox.struct.BoxInfo;
	import imvu.rbox.struct.CGamePlayerInfo;
	
	import org.dstart.object.memo.MemoObject;

	public class MainGameObject extends Sprite
	{
		public var myInfo:MyInfoObject;			//	当前玩家的信息
		public var myGame:MainGamePlay;			//	当前玩家的方块对象
		
		public var mcDrag:Sprite;				//	拖动滑片
		
		public var mcSeat1:PlayerInfoObject;	//	1 号坐位玩家信息
		public var mcSeat2:PlayerInfoObject;	//	2 号坐位玩家信息
		public var mcSeat3:PlayerInfoObject;	//	3 号坐位玩家信息
		public var mcSeat4:PlayerInfoObject;	//	4 号坐位玩家信息
		public var mcSeat5:PlayerInfoObject;	//	5 号坐位玩家信息
		
		public var mcTime:TimeObject;		//	计时器对象
		public var mcAction:ActionObject;	//	控制器对象
		
		public var btnChange:SimpleButton;	//	修改房间信息按钮（限房主）
		public var btnQuit:SimpleButton;	//	退出房间按钮
		public var btnReady:SimpleButton;	//	准备按钮（针对非房主玩家）
		public var btnStart:SimpleButton;	//	开始按钮（针对房主）
		
		public var mcBg:Sprite;				//	游戏背景
		public var mcBomb:MovieClip;		//	爆炸效果
		public var mcReady:MovieClip;		//	准备标识
		public var mcScore:ScoreObject;		//	结算面板

		public function MainGameObject()
		{
			InitObject();
			InitListener();
		}
		
		public function DeleteListener():void
		{
			
		}
		
		//	停止时间，同时停止正在运行的游戏
		public function StopTime():void
		{
			this.mcTime.StopTime();		
			this.mcAction.box = null;	
			this.myGame.InitGameBase();
		}
		
		//	有玩家爆气,更新玩家数据
		public function UpdataGameData(uID:String, array:Array):void
		{
			if(!this.myGame.isGameOver)
			{
				if(this.myInfo.info.userID.indexOf(uID) >= 0)
				{
					this.mcBomb.gotoAndPlay(2);					
				}
				else
				{
					// GStatic.Trace("取得数据条目:" + array.length);
					
					for(var i:int = 0; i < array.length; i++)
					{
						// GStatic.Trace("添加数据: " + array[i]);
						this.myGame.UpdataBgdata(array[i], true);
					}
					
					for(var m:int = 1; m <= 5; m++)
					{
						var pObj:PlayerInfoObject = this["mcSeat" + m];				
						if(pObj.info)
						{
							if(pObj.info.userID.indexOf(uID) >= 0)
							{
								pObj.isBomb = true;										
							}
						}
					}
				}							
			}			
		}
		
		//	显示结算面板
		public function ShowScore(array:Array, num:Number = 0):void
		{
			this.mcScore.ShowScore(array, num);
			this.parent.addChild(this.mcScore);
		}
		
		//	指定 ID 的玩家离开房间
		public function DoUserQuit(uID:String):void
		{
			if(this.myInfo.info.userID.indexOf(uID) >= 0)
			{
				//	如果是自己离开房间
				// trace("自己离开房间了");
				this.myInfo.info = null;
				RushGameBase(false);
			}
			else
			{
				// trace("有其它玩家(" + uID + ")离开房间了");
				for(var m:int = 1; m <= 5; m++)
				{
					var pObj:PlayerInfoObject = this["mcSeat" + m];				
					if(pObj.info)
					{
						if(pObj.info.userID.indexOf(uID) >= 0)
						{
							pObj.info = null;												
						}
					}
				}
			}
		}
		
		//	加入游戏，此时要根据房主标识确定是否允许调整
		public function JoinGame(isMaster:Boolean):void
		{			
			if(!GStatic.isGameStart)
			{
				this.mcReady.visible = false;
				this.mcBomb.gotoAndStop(1);
				this.btnReady.visible = !isMaster;
				this.btnStart.visible = isMaster;
				// this.btnChange.visible = isMaster;
				
				for(var i:int = 1; i <= 5; i++)
				{
					var pObj:PlayerInfoObject = this["mcSeat" + i];
					if(pObj.info)
					{
						pObj.enabled = isMaster;						
					}						
				}
			}
		}
		
		public function ChangeFlag(uID:String):void
		{
			for(var i:int = 1; i <= 5; i++)
			{
				var pObj:PlayerInfoObject = this["mcSeat" + i];
				if(pObj.info)
				{
					if(pObj.info.userID.indexOf(uID) >= 0)
					{
						pObj.isReady = false;
					}
				}
			}
		}
		
		//	显示相应玩家的游戏结束消息
		public function ShowGameOver(uID:String):void
		{
			// trace("当前退出玩家ID:" + uID);
			
			for(var m:int = 1; m <= 5; m++)
			{
				var pObj:PlayerInfoObject = this["mcSeat" + m];				
				if(pObj.info)
				{
					// trace("检测到的信息是:" + pObj.info.userID)
					
					if(pObj.info.userID.indexOf(uID) >= 0)
					{
						pObj.isGameOver = true;
						this.mcAction.StopKeyListener();
						if(pObj.info.userID == GStatic.myInfo.userID)
						{
							GStatic.isGameStart = false;
						}
						break;
					}
				}
			}
		}
		
		//	整理屏幕,并且清除所有对象的事件侦听
		public function RushGameBase(isJoin:Boolean = true):void
		{
			GStatic.myInfo.cleanLines = 0;
			GStatic.myInfo.userScore = 0;			
			GStatic.nowRoom.gameData = new Array(); 
			GStatic.isGameStart = false;			
			
			StopTime();
			
			this.myInfo.info = GStatic.myInfo;
			this.mcBomb.gotoAndStop(1);
			this.mcReady.visible = false;
			this.myGame.InitGameBase();
			this.btnQuit.visible = true;
			this.mcAction.InitAction();
			
			for(var m:int = 1; m <= 5; m++)
			{
				var pObj:PlayerInfoObject = this["mcSeat" + m];
				pObj.InitGameBase();
				if(!isJoin)
				{
					pObj.info = null;
				}
				else if(GStatic.isRoomMaster)
				{
					if(pObj.info)
					{
						pObj.enabled = true;
					}
					else
					{
						pObj.enabled = false;
					}
				}						
			}
			
			JoinGame(GStatic.isRoomMaster);
		}
		
		public function RushUserInfo(uInfo:CGamePlayerInfo):void
		{
			// trace("当前玩家:: " + GStatic.myInfo.userName + " is master:: " + GStatic.isRoomMaster);
			
			if(uInfo)
			{
				if(uInfo.userID == GStatic.myInfo.userID)
				{
					// GStatic.myInfo.clientID = uInfo.clientID;
					GStatic.myInfo.seatID = uInfo.seatID;
					GStatic.myInfo.gameSpeed = GStatic.nowRoom.gameSpeed + Math.floor(GStatic.myInfo.cleanLines/GStatic.UP_LEVEL_LINE);
					GStatic.myInfo.gameSpeed = (GStatic.myInfo.gameSpeed >= GStatic.MAX_SPEED) ? GStatic.MAX_SPEED : GStatic.myInfo.gameSpeed;
					
					uInfo.cleanLines = GStatic.myInfo.cleanLines;
					uInfo.gameSpeed = GStatic.myInfo.gameSpeed;
							
					if(uInfo.isReady)
					{
						this.btnReady.visible = false;
						this.btnStart.visible = false;
						// this.myGame.InitGameBase();
						if(!GStatic.isGameStart)
						{		
							this.mcReady.visible = !GStatic.isRoomMaster;
						}
						else
						{
							this.mcReady.visible = false;
						}		
					}
					
					this.myInfo.info = uInfo;
					// this.myGame.RushBgData(uInfo.gameData);
					this.myGame.hotPercent = Math.floor(uInfo.nowPower / GStatic.MAX_POWER * 100);
					
					if(uInfo.isPower && GStatic.isGameStart)
					{
						this.mcBomb.gotoAndPlay(2);
					}			
				}
				else
				{				
					for(var m:int = 1; m <= 5; m++)
					{
						var pObj:PlayerInfoObject = this["mcSeat" + m];
						if(!pObj.info)
						{
							pObj.enabled = false;
						}
						
						// trace(pObj.seatID + " :: " + uInfo.seatID);
						
						if(pObj.seatID == uInfo.seatID)
						{
							pObj.info = uInfo;
							if(!GStatic.isGameStart)
							{
								pObj.enabled = GStatic.isRoomMaster;
							}
						}					
					}
				}
			}
		}
		
		private function InitPlayerSeat():void
		{
			this.myInfo.info = null;
			
			for(var i:int = 1; i <= 5; i++)
			{
				var pObj:PlayerInfoObject = this["mcSeat" + i];
				
				pObj.seatID = 0;
				pObj.info = null;
			}
		}
		
		public function RushUsers(array:Array):void
		{			
			InitPlayerSeat();
			
			// trace("更新房间用户列表:: " + array.length);
			
			//**
			for(var i:int = 0; i < array.length; i++)
			{
				var uInfo:CGamePlayerInfo = array[i];
				// trace("当前用户信息：" + uInfo);
				if(uInfo.userID == GStatic.myInfo.userID)
				{
					// trace("这个用户是自己!" + GStatic.myInfo.userID);
					// GStatic.myInfo.clientID = uInfo.clientID;
					GStatic.myInfo.seatID = uInfo.seatID;
					GStatic.myInfo.gameSpeed = GStatic.nowRoom.gameSpeed + Math.floor(GStatic.myInfo.cleanLines/GStatic.UP_LEVEL_LINE);
					GStatic.myInfo.gameSpeed = (GStatic.myInfo.gameSpeed >= GStatic.MAX_SPEED) ? GStatic.MAX_SPEED : GStatic.myInfo.gameSpeed;

					uInfo.cleanLines = GStatic.myInfo.cleanLines;
					uInfo.gameSpeed = GStatic.myInfo.gameSpeed;
					
					if(uInfo.isReady)
					{
						this.btnReady.visible = false;
						this.btnStart.visible = false;						
					}
					this.myInfo.info = uInfo;
					// this.myGame.RushBgData(uInfo.gameData);
					this.myGame.hotPercent = Math.floor(uInfo.nowPower / GStatic.MAX_POWER * 100);
					
					ChangeSeatID();
					break;
				}
			}
			
			// trace("当前用户坐号:" + GStatic.myInfo.seatID);			
			//**
			//try
			//{
			for(var m:int = 1; m <= 5; m++)
			{
				var pObj:PlayerInfoObject = this["mcSeat" + m];
				pObj.enabled = false;
				
				for(var j:int = 0; j < array.length; j++)
				{
					var pInfo:CGamePlayerInfo = array[j];
					if(pObj.seatID == pInfo.seatID)
					{
						pObj.info = pInfo;
						if(!GStatic.isGameStart)
						{
							pObj.enabled = GStatic.isRoomMaster;
							
							// trace(pObj.name + " :: " + pObj.info.userName + " :: " + pObj.seatID);
						}
					}
				}				
			}
			//}
			//catch(e:*)
			//{
			//	trace("显示用户信息时出错");
			//}//**/
		}
		
		//	重新修改玩家的坐位号
		private function ChangeSeatID():void
		{
			for(var i:int = 1; i <= 5; i++)
			{
				var pObj:PlayerInfoObject = this["mcSeat" + i];
				if(pObj.seatID == 0)
				{
					if(i >= GStatic.myInfo.seatID)
					{
						pObj.seatID = i + 1;
					}
					else
					{
						pObj.seatID = i;
					}
					// pObj.seatID = (GStatic.myInfo.seatID + i) % 6;
					// pObj.seatID = (pObj.seatID == 0) ? 6 : pObj.seatID;
					// trace("修改房间坐号, 当前玩家坐号：" + GStatic.myInfo.seatID + "," + pObj.name + " 的坐号是 : " + pObj.seatID);
				}
			}
		}
	
		public function StartGame():void
		{
			GStatic.isGameStart = true;		
			
			// trace("StartGame!!");
			
			this.mcTime.StartTime();
			this.btnQuit.visible = false;
			
			HiddenAllFlag();
			DoStartGame();
		}
		
		//-----------------------------------------------------
		
		private function InitObject():void
		{
			MemoObject.create(this.btnChange, "Change room rule");
			MemoObject.create(this.btnQuit, "Quit room");
			
			mcBomb.gotoAndStop(1);
			mcReady.visible = false;
			mcScore.visible = false;
			
			// btnChange.visible = false;
		}
		
		private function InitListener():void
		{
			for(var i:int = 1; i <= 5; i++)
			{
				var pObj:PlayerInfoObject = this["mcSeat" + i];
				pObj.addEventListener(ActionEvent.TICK_USER, onTickUserEvent);
				pObj.addEventListener(ActionEvent.CLOSE_SEAT, onCloseSeatEvent);
			}
			
			this.mcDrag.addEventListener(MouseEvent.MOUSE_DOWN, onDragStart);
			this.mcDrag.addEventListener(MouseEvent.MOUSE_UP, onDragStop);
			
			//	各按钮事件
			this.btnReady.addEventListener(MouseEvent.CLICK, onClickButtons);
			this.btnStart.addEventListener(MouseEvent.CLICK, onClickButtons);
			this.btnChange.addEventListener(MouseEvent.CLICK, onClickButtons);
			this.btnQuit.addEventListener(MouseEvent.CLICK, onClickButtons);
			
			//	各对象事件
			this.mcAction.addEventListener(ActionEvent.LEFT_MOVE, onLeftMoveEvent);
			this.mcAction.addEventListener(ActionEvent.RIGHT_MOVE, onRightMoveEvent);
			this.mcAction.addEventListener(ActionEvent.DOWN_MOVE, onDownMoveEvent);
			this.mcAction.addEventListener(ActionEvent.CHANGE_BOX, onChangeBoxEvent);
			this.mcAction.addEventListener(ActionEvent.FASET_DOWN, onFastDownEvent);
			// this.mcAction.addEventListener(MouseEvent.CLICK, onTestChangebox);		
			
			//	主控制面板事件
			this.myGame.addEventListener(ActionEvent.BOX_DONE, onBoxMoveDoneEvent);	
			this.myGame.addEventListener(ActionEvent.GAME_DONE, onGameDoneEvent);
			this.myGame.addEventListener(ActionEvent.UPDATA_LINE, onUpdataLineEvent);
		}
		
		private function onDragStart(e:MouseEvent):void
		{
			this.dispatchEvent(new Event(TitleEvent.START_DRAG));
		}
		
		private function onDragStop(e:MouseEvent):void
		{
			this.dispatchEvent(new Event(TitleEvent.STOP_DRAG));
		}
		
		//	发送踢除玩家的事件
		private function onTickUserEvent(e:ActionEvent):void
		{
			this.dispatchEvent(new ActionEvent(ActionEvent.TICK_USER, e.data));
		}
		
		//	房间关闭/开启事件
		private function onCloseSeatEvent(e:ActionEvent):void
		{
			this.dispatchEvent(new ActionEvent(ActionEvent.CLOSE_SEAT, e.data));
		}
		
		private function onUpdataLineEvent(e:ActionEvent):void
		{
			// trace("收到更新游戏数据");
			this.dispatchEvent(new ActionEvent(ActionEvent.UPDATA_LINE, e.data));
		}
		
		private function onLeftMoveEvent(e:ActionEvent):void
		{
			// trace("执行左移");
			if(GStatic.isGameStart)
			{
				this.myGame.ChangePlace(BoxEvent.LEFT_MOVE);
			}
		}
		
		private function onRightMoveEvent(e:ActionEvent):void
		{
			// trace("执行右移");
			if(GStatic.isGameStart)
			{
				this.myGame.ChangePlace(BoxEvent.RIGHT_MOVE);
			}
		}

		private function onDownMoveEvent(e:ActionEvent):void
		{
			// trace("快速下移");
			if(GStatic.isGameStart)
			{
				this.myGame.ChangePlace(BoxEvent.DOWN_MOVE);
			}
		}

		private function onChangeBoxEvent(e:ActionEvent):void
		{
			// trace("修改形状");
			if(GStatic.isGameStart)
			{
				this.myGame.ChangeShape();
			}
		}
		
		private function onFastDownEvent(e:ActionEvent):void
		{
			if(GStatic.isGameStart)
			{
				this.myGame.ChangePlace(BoxEvent.FAST_DOWN);
			}
		}
		
		private function onBoxMoveDoneEvent(e:ActionEvent):void
		{
			this.dispatchEvent(new ActionEvent(ActionEvent.BOX_DONE, e.data));
			
			// trace("安装下一个方块");
			this.myGame.boxObject = this.mcAction.box;			
			
			SetNextBox();
		}
		
		private function onGameDoneEvent(e:ActionEvent):void
		{
			this.mcAction.StopKeyListener();
			this.dispatchEvent(new ActionEvent(ActionEvent.GAME_DONE, e.data));
			// trace("已经发现游戏结束了...");
		}

		/**
		private function onTestChangebox(e:MouseEvent):void
		{
			// trace("OK");
			ChangeBox(Math.floor(Math.random() * 13 + 1));
			// ChangeBox(1);
		}		
		
		private function ChangeBox(boxID:Number = 0):void
		{
			// trace("changeBox::", boxID);
			var boxObj:BoxInfo = new BoxInfo();
			if(boxID <= 0)
			{
				boxObj.id = GStatic.nowRoom.nowBox;
			}
			else
			{
				boxObj.id = boxID;
			}
			boxObj.arrow = Math.floor(Math.random() * 4);
			
			// trace("getData::" + boxObj.boxData);
			
			this.mcAction.box = boxObj;			
		}//**/
		
		private function onClickButtons(e:MouseEvent):void
		{
			switch(e.target)
			{
				case this.btnReady :
					//DoStartGame();
					this.dispatchEvent(new ActionEvent(ActionEvent.IS_READY));
					break;
				
				case this.btnStart :
					//DoStartGame();
					this.dispatchEvent(new ActionEvent(ActionEvent.IS_READY));
					break;
				
				case this.btnChange :
					GStatic.isShowInfo = !GStatic.isShowInfo;
					break;
				
				case this.btnQuit :
					this.dispatchEvent(new ActionEvent(ActionEvent.QUIT_ROOM));
					break;
			}
		}
		
		//--------------------------------------------------------
		
		private function HiddenAllFlag():void
		{
			this.mcReady.visible = false;
			this.mcBomb.gotoAndStop(1);
			
			for(var i:int = 1; i <= 5; i++)
			{
				var pObj:PlayerInfoObject = this["mcSeat" + i];
				pObj.isReady = false;
				pObj.enabled = false;
			}
		}
		
		//	点击 游戏开始 按钮
		private function DoStartGame():void
		{
			// trace("游戏开始");
			this.btnReady.visible = false;
			this.btnStart.visible = false;
			
			// GStatic.myInfo = new CGamePlayerInfo();
			// GStatic.myInfo.gameSpeed = 1;
			
			// GStatic.nowRoom = new CGameRoomInfo();
			// GStatic.nowRoom.gameData = GetRandomArray();
			
			// trace("当前游戏数组:" + GStatic.nowRoom.gameData);
			
			SetNextBox();
			SetNextBox();
			
			this.myGame.boxObject = this.mcAction.box;			
			
			SetNextBox();
		}
		
		private function SetNextBox():void
		{
			// trace("设置下一个要出现的方块");
			
			var bInfo:BoxInfo = new BoxInfo();
			bInfo.id = GStatic.nowRoom.nowBox;
			bInfo.arrow = Math.floor(Math.random() * 4);
			
			if(bInfo.id == 0)
			{
				// trace("方块 ID = 0, 检测到已经没有方块.. 游戏结束");
				return;
			}
						
			this.mcAction.box = bInfo;//new BoxInfo(GStatic.nowRoom.box);
		}
		
		private function GetRandomArray():Array
		{
			var tArray:Array = new Array();
			var maxLength:Number = 100;
			for(var i:int = 0; i < maxLength; i++)
			{
				tArray.push(Math.floor(Math.random() * 14) + 1);
			}
			
			return tArray;
		}
	}
}